//
//  SignAPI.swift
//  SwiftSign
//
//  Created by continue on 2021/4/25.
//

import Foundation
import Moya

//let endpointClosure = { (target: TargetType) -> Endpoint in
//    let url = target.baseURL.absoluteString + target.path
//     let endpoint = Endpoint(
//         url: url,
//         sampleResponseClosure: { .networkResponse(200, target.sampleData) },
//         method: target.method,
//         task: target.task,
//         httpHeaderFields: target.headers
//     )
//    return endpoint
//}
//
//let moyaProvider = MoyaProvider<SignAPI>(endpointClosure: endpointClosure)

enum SignAPI {
    case userInit
    case getRandUser
    case userRegiter(username: String, password: String)
    case loginSendCode(phone: String)
    case phoneLogin(phone: String, code: String)
}



extension SignAPI: TargetType {


    var baseURL: URL {
        return URL(string: Configs.Network.signBaseUrl)!
    }
    
    var path: String {
        switch self {
        case .userInit: return  "?method=user.init"
        case .getRandUser: return "?method=user.getRandUser"
        case .userRegiter: return "?method=user.userReg"
        case .loginSendCode: return "?method=user.sendSmsCode"
        case .phoneLogin: return "?method=user.phoneLogin2"
        }
    }
    var headers: [String : String]? {
        return nil
    }
        
    var method: Moya.Method {
        return .post
    }
    
    var parameters: [String: Any]? {
        let parameters = Parameters()
        var params = parameters.getCommonParameters()
        switch self {
        case .userRegiter(let username, let password):
            params["username"] = username
            params["password"] = password
        case .loginSendCode(let phone):
            params["type"] = "phoneLogin"
            params["phone"] = phone
        case .phoneLogin(let phone, let code):
            params["code"] = code
            params["phone"] = phone
        default:
            break
        }
        let sort = parameters.sort(params: params) + Configs.App.appKey
        let sign = sort.md5
        params["sign"] = sign
        return params
    }
        
    var sampleData: Data {
        return "{}".data(using: String.Encoding.utf8)!
    }
    
    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }
        
    var task: Task {
        
        if let parameters = parameters {
            return .requestParameters(parameters: parameters, encoding: parameterEncoding)
        }
        return .requestPlain
    }
    
    
}

